package tools.texture.view {
	import tools.event.ProjectEvent;
	import tools.event.TextureEvent;
	import tools.model.EditorConfig;
	import tools.model.FrameInfo;
	import tools.utils.bindSetter;

	import org.aswing.event.SelectionEvent;
	import org.robotlegs.mvcs.Mediator;

	import flash.events.Event;

	/**
	 * 角色编辑器的部分
	 * @author zhangming.luo
	 */
	public class FrameEditorMediator extends Mediator {
		[Inject]
		public var view : FrameEditorPanel;
		[Inject]
		public var config : EditorConfig;

		override public function onRegister() : void {
			super.onRegister();
			addViewListener(ProjectEvent.BROWSE_TEXTURE_IMG, dispatch);
			addViewListener(ProjectEvent.BROWSE_TEXTURE_CONFIG, dispatch);
			addViewListener(TextureEvent.NEW_FRAME, dispatch);
			addViewListener(TextureEvent.UPDATE_FRAME, dispatch);
			addViewListener(TextureEvent.DELETE_FRAME, dispatch);
			addContextListener(ProjectEvent.TEXTURE_IMG_LOADED, onTextureImgLoaded);
			view.tileList.addEventListener(SelectionEvent.LIST_SELECTION_CHANGED, onTileChange);
			view.frameList.addEventListener(SelectionEvent.LIST_SELECTION_CHANGED, onFrameChange);
			bindSetter(handleFrameChange, config, "allFrameList").watch();
			bindSetter(handleTileChange, config, "allTileList").watch();
			view.browseConfigButton.setEnabled(false);
		}

		private function onTextureImgLoaded(e : Event) : void {
			view.browseConfigButton.setEnabled(true);
		}

		private function handleTileChange() : void {
			view.tileList.setListData(config.allTileList);
			view.tileList.setSelectedIndex(0);
		}

		private function handleFrameChange() : void {
			view.frameList.setListData(config.allFrameList);
			view.frameList.setSelectedIndex(0);
		}

		private function onFrameChange(event : SelectionEvent) : void {
			var frameInfo : FrameInfo = view.frameList.getSelectedValue();
			if (frameInfo) {
				view.framePreviewContainer.setFrame(frameInfo);
				view.tileList.setSelectedValues(frameInfo.tileList);
			} else {
				view.framePreviewContainer.setFrame(null);
				view.tileList.setSelectedValues([]);
			}
		}

		private function onTileChange(event : SelectionEvent) : void {
			view.tilePreview.setTileList(view.tileList.getSelectedValues());
		}
	}
}
